<template>
  <view class="quick-entry" :style="Object.assign({}, quickEntryStyle, { pointerEvents: isEditMode ? 'none' : 'auto' })" @click.stop="handleEditModeClick">
    <view
        class="entry-item"
        v-for="(item, index) in entryList"
        :key="item.id || index"
        @click.stop="toCategory(item)"
        :style="itemStyle"
    >
      <!--    <view
              class="entry-item"
              v-for="(item, index) in entryList" 
              :key="item.id || index"
          >-->
      <view class="icon-placeholder">
        <img
            :src="getFullImgUrl(item.icon)"
            mode="aspectFill"
            style="width: 100%; height: 100%; border-radius: 16px;"
        />
      </view>
      <view class="entry-text" :style="getTextStyle(item)">{{ item.name }}</view>
    </view>
  </view>
</template>

<script>
import { shopList } from "../../api/newShop/index";

function parseLayout(layout) {
  if (typeof layout === 'string') {
    try {
      return JSON.parse(layout);
    } catch (e) {
      return {};
    }
  }
  return layout || {};
}

export default {
  props: {
    config: {
      type: Object,
      default: () => ({})
    },
    layout: {
      type: [Object, String],
      default: () => ({})
    },
    isEditMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 快速入口配置列表
      entryList: [],
      // 默认跳转路径（当项中未指定时使用）
      defaultCategoryUrl: '/rightType/second/index',
      resLayout: '' // 保存接口返回的layout字符串
    }
  },
  mounted() {
    this.getShopList();
  },
  watch: {
    layout: {
      handler() {
        console.log('QuickEntry layout changed:', this.layout, this.parsedLayout, this.quickEntryStyle);
        this.$forceUpdate();
      },
      deep: false
    }
  },
  computed: {
    parsedLayout() {
      try {
        return typeof this.resLayout === 'string' ? JSON.parse(this.resLayout) : (this.resLayout || {});
      } catch (e) {
        return {};
      }
    },
    quickEntryStyle() {
      let columns = 4;
      // 兼容clas为字符串或数字
      const clasNum = Number(this.parsedLayout && this.parsedLayout.clas);
      if (clasNum && [3,4,5].includes(clasNum)) {
        columns = clasNum;
      } else if (this.config?.style?.columns) {
        columns = this.config.style.columns;
      }
      const style = this.config?.style || {};
      const bgc = this.parsedLayout && this.parsedLayout.clas_bgc;
      console.log('parsedLayout in quickEntryStyle:', this.parsedLayout, 'columns:', columns);
      return {
        marginTop: style.blockMargin ? style.blockMargin + 'px' : '',
        marginBottom: style.blockMargin ? style.blockMargin + 'px' : '',
        display: 'grid',
        gridTemplateColumns: `repeat(${columns}, 1fr)`,
        gap: style.itemGap ? style.itemGap + 'px' : '12px',
        background: bgc || '#fff',
        borderRadius: '12px',
        padding: '16px 0 8px 0',
        width: '95%',
        marginLeft: '.6rem',
        cursor: 'pointer',
        transition: 'all 0.3s ease',
      };
    },
    itemStyle() {
      return {};
    },
  },
  methods: {
    getTextStyle(item) {
      const style = item.style || {};
      return {
        fontSize: style.fontSize ? style.fontSize + 'px' : '14px',
        color: style.textColor || '#666',
      };
    },
    toCategory(item) {
      // 编辑模式下阻止导航
      if (this.isEditMode) {
        return;
      }
      
      uni.navigateTo({
        url: `${this.defaultCategoryUrl}?clas_id=${item.id}`
      });
    },
    getFullImgUrl(thumb) {
      const baseUrl = getApp().globalData.baseUrl;
      return thumb.startsWith("http") ? thumb : baseUrl + thumb;
    },
    getShopList() {
      shopList().then(res => {
        if (res.code === 200) {
          this.entryList = res.data.clas;
          this.resLayout = res.data.layout;
        }
      }).catch(err => {
        console.error('获取分类失败：', err);
      });
    },
    handleClick(event) {
      // 检查是否在编辑模式下
      if (this.isEditMode) {
        // 编辑模式下，阻止默认行为
        event.preventDefault();
        event.stopPropagation();
        
        this.$emit('component-click', 'quickEntry', {
          items: this.entryList
        }, event);
      }
      // 非编辑模式下，允许正常的点击行为
    },
    handleEditModeClick(event) {
      if (this.isEditMode) {
        event.preventDefault();
        event.stopPropagation();
      }
    },
    updateConfig(config) {
      if (config && config.items) {
        this.entryList = config.items;
      }
      this.$forceUpdate();
    }
  }
}
</script>
<style scoped>
.quick-entry {
  margin-top: 10px;
  width: 95%;
  margin-left: .6rem;
  display: grid;
  gap: 12px;
  background: #fff;
  border-radius: 12px; 
  padding: 16px 0 8px 0;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.entry-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.icon-placeholder {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  margin-bottom: 8px;
}
.entry-text {
  font-size: 14px;
  color: #666;
}
</style>